package com.sise.bl.dao.impl;

import com.sise.bl.dao.CartDao;
import com.sise.bl.entity.Cart;
import com.sise.bl.entity.Item;
import com.sise.bl.entity.User;
import org.hibernate.query.NativeQuery;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository(value = "cartDao")
@SuppressWarnings("all")
public class CartDaoImpl extends BaseDaoImpl<Cart> implements CartDao {

    @Override
    public List<Cart> hasCart(Integer uid, Integer pid) {
        String sql = "select c" +
                " from Product p join Cart c on p.pid=c.product.pid join User u on c.user.uid=u.uid " +
                "where u.uid=:uid and p.pid=:pid";
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("uid", uid);
        params.put("pid", pid);

        Query query = this.getCurrentSession().createQuery(sql);

        for (String key : params.keySet()) {
            query.setParameter(key, params.get(key));
        }
        List<Cart> carts = query.list();

        return carts;
    }

    @Override
    public void updateCart(Cart cart) {
        update(cart);
    }

    @Override
    public void insertCart(Cart cart) {
        save(cart);
    }

    @Override
    public List<Cart> selectCartsByUid(Integer uid) {
        String sql = "select c " +
                "from Cart c join User u on c.user.uid=u.uid " +
                "where c.user.uid=:uid";
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("uid", uid);
        List<Cart> carts = find(sql, params);
        return carts;
    }

    @Override
    public Cart selectCartsByCid(Integer cid) {
        return get(cid);
    }

    @Override
    public void deleteCart(Cart cart) {
        delete(cart);
    }

    @Override
    public void deleteCartByUid(String uid) {
        String sql = "delete from Cart c where c.user.uid=?0";
        Query query = this.getCurrentSession().createQuery(sql);
        query.setParameter(0,Integer.valueOf(uid));
        query.executeUpdate();
    }

    @Override
    public void deleteCartByPid(Integer pid) {
        String sql = "delete from Cart c where c.prodcut.pid=?0";
        Query query = this.getCurrentSession().createQuery(sql);
        query.setParameter(0,pid);
        query.executeUpdate();
    }

}
